# serializers.py
from rest_framework import serializers
from .models import Position, Answer, Question, Product


class PositionSerializer(serializers.ModelSerializer):
    video_path = serializers.FileField(required=False)
    image_path = serializers.ImageField(required=False)
    position_intro_link = serializers.URLField(required=False, allow_blank=True)
    culture_highlight_link = serializers.URLField(required=False, allow_blank=True)
    video_more_link = serializers.URLField(required=False, allow_blank=True)
    image_more_link = serializers.URLField(required=False, allow_blank=True)
    exhibition_outline_link = serializers.URLField(required=False, allow_blank=True)
    coordinate = serializers.CharField(required=False, allow_blank=True)
    exhibition_outline = serializers.CharField(required=False, allow_blank=True)
    culture_highlight = serializers.CharField(required=False, allow_blank=True)
    class Meta:
        model = Position
        fields = '__all__'

    def get_video_path(self, obj):
        if obj.video_path:
            return obj.video_path.url
        return None

    def get_image_path(self, obj):
        if obj.image_path:
            return obj.image_path.url
        return None

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ['id', 'text', 'is_correct']

class QuestionSerializer(serializers.ModelSerializer):
    answers = AnswerSerializer(many=True, required=False)

    class Meta:
        model = Question
        fields = ['id', 'text', 'question_type', 'answers']

    def create(self, validated_data):
        answers_data = validated_data.pop('answers', [])
        question = Question.objects.create(**validated_data)
        for answer_data in answers_data:
            Answer.objects.create(question=question, **answer_data)
        return question
class ProductSerializer(serializers.ModelSerializer):
    class Meta:
        model = Product
        fields = ['id', 'name', 'price', 'discounted_price', 'detail_link', 'image']